from config import ROUTE_CODE_MAP
from typing import Union
from config import LIMIT,OFFSET

def orm2dict(orm,filter=[]):
    if isinstance(orm,list):
        return [orm2dict(i) for i in orm]
    if not isinstance(orm,dict):
        orm_dict = orm.__dict__
    else:
       orm_dict = orm
    ret_dict = {}
    for k,v in orm_dict.items():
        if k == '_sa_instance_state' or k in filter:
            continue
        if isinstance(v,list):
            ret_dict[k] = orm2dict(v)
        else:
            ret_dict[k] = v
    return ret_dict

def ret_route(code=200,data={}):
    if isinstance(data,str):
        return {'code':code,'msg':ROUTE_CODE_MAP.get(code,'未知错误'),'data':data}
    if type(data)not in(dict,list):
        return data
    return {'code':code,'msg':ROUTE_CODE_MAP.get(code,'未知错误'),'data':data}

def limit_framt(data:dict):
    limit = int(data.pop('limit') if 'limit' in data else LIMIT)
    offset = int(data.pop('offset') if 'limit' in data else OFFSET)
    if offset:
        offset -= 1
    return limit,offset
